import os
import shutil
from math import ceil

def split_files(source_folder, files_per_folder=1000):

    print(source_folder,'文件拆分现在开始。。。')

    # 确保源文件夹存在
    if not os.path.exists(source_folder):
        print(f"错误：源文件夹 '{source_folder}' 不存在！")
        return
    
    # 获取源文件夹中的所有文件
    files = [f for f in os.listdir(source_folder) if os.path.isfile(os.path.join(source_folder, f))]
    
    # 计算需要创建的子文件夹的数量
    num_folders = ceil(len(files) / files_per_folder)
    
    # 拆分文件
    for i in range(num_folders):
        # 创建目标子文件夹名称
        target_folder_name = f"{os.path.basename(source_folder)}_{i+1}"
        target_folder = os.path.join(os.path.dirname(source_folder), target_folder_name)
        os.makedirs(target_folder, exist_ok=True)
        
        # 计算当前子文件夹应该包含的文件范围
        start_index = i * files_per_folder
        end_index = min((i + 1) * files_per_folder, len(files))
        
        # 复制文件到子文件夹
        for file_name in files[start_index:end_index]:
            src_path = os.path.join(source_folder, file_name)
            dst_path = os.path.join(target_folder, file_name)
            shutil.copy2(src_path, dst_path)

# 使用示例 /path/to/source/folder
source_folder = r"D:\北京伊吕科技\应用场景\数据标注\深启科技\yw\sld"
split_files(source_folder)